package org.hzy.test1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hzy.entity.Blobs;

public class BlobTest {

	/**
	 * @param args
	 */

	static Configuration con = new Configuration().configure();
	static SessionFactory fac = con.buildSessionFactory();
	static Session sess = fac.getCurrentSession();

	public static void save_blob() {
		Blobs blo = new Blobs();
		blo.setBid(1);
		blo.setBname("ONE");
		blo.setBcontent("XX");
		Blob b = null;

		try {
			FileInputStream file = new FileInputStream("c:"+File.separator+"a.jpg");

			b = Hibernate.createBlob(file);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		blo.setBphoto(b);
		Transaction tran = sess.beginTransaction();
		sess.save(blo);

		tran.commit();
	}

	static void get_blob() {
		Transaction tran = sess.beginTransaction();
		Blobs bl = (Blobs) sess.get(Blobs.class, 1);
		try {
			
			InputStream is = bl.getBphoto().getBinaryStream();

			FileOutputStream out = new FileOutputStream("c:" + File.separator
					+ "xxy1.jpg");
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		tran.commit();
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		get_blob();
	}

}
